<template>
  <div class="message-panel" v-loading="loading">
    <div class="message-container">
      <div class="message-list" ref="messageListRef">
        <div v-if="messages.length === 0" class="empty-message">
          <el-empty description="暂无消息" />
        </div>
        <template v-else>
          <div v-for="(message, index) in messages" :key="index" class="message-item" :class="[message.type]">
            <div class="message-row">
              <div v-if="message.type === 'received'" class="avatar">
                <img :src="message.avatar || defaultAvatar" alt="头像" @error="handleImageError">
              </div>
              <div class="message-content">
                <div v-if="message.type === 'received'" class="sender-name">{{ message.sender }}</div>
                <div class="bubble-wrapper">
                  <div class="message-bubble" v-if="!message.file" v-html="message.content"></div>
                  <div v-else class="media-container">
                    <!-- 文件 -->
                    <div v-if="message.file.type === 0" class="file-item" @click="downloadFile(message.file)">
                      <div class="file-icon">
                        <el-icon>
                          <Document />
                        </el-icon>
                      </div>
                      <div class="file-info">
                        <div class="file-name">{{ message.file.filename }}</div>
                        <div class="file-action">点击下载</div>
                      </div>
                    </div>

                    <!-- 视频 -->
                    <div v-else-if="message.file.type === 3" class="video-container">
                      <video controls class="media-player">
                        <source :src="getMediaUrl(message.file)" type="video/mp4">
                        您的浏览器不支持视频播放
                      </video>
                    </div>

                    <!-- 音频 -->
                    <div v-else-if="message.file.type === 2" class="audio-container">
                      <audio controls class="media-player">
                        <source :src="getMediaUrl(message.file)" type="audio/mpeg">
                        您的浏览器不支持音频播放
                      </audio>
                    </div>

                    <!-- 图片 -->
                    <div v-else class="file-img">
                      <el-image :src="getMediaUrl(message.file)" :previewSrcList="[getMediaUrl(message.file)]"
                        fit="cover" />

                    </div>
                  </div>
                  <div class="message-time">{{ formatTime(message.time) }}</div>
                </div>
              </div>
              <div v-if="message.type === 'sent'" class="avatar">
                <img :src="message.avatar || defaultAvatar" alt="头像" @error="handleImageError">
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>

    <div class="message-input">
      <el-input v-model="inputMessage" type="textarea" :rows="2" placeholder="请输入消息..." resize="none"
        @keyup.enter="sendMessage" />
      <div class="message-actions">
        <span class="tip">按Enter发送</span>
        <div class="action-buttons">
          <el-upload class="file-upload" action="#" :auto-upload="false" :show-file-list="false"
            :on-change="handleFileChange">
            <el-button type="primary" plain>
              <el-icon>
                <Folder />
              </el-icon>
            </el-button>
          </el-upload>
          <el-button type="primary" :disabled="!inputMessage.trim() && !selectedFile || !flightNo"
            @click="sendMessage">发送</el-button>
        </div>
      </div>
      <div v-if="selectedFile" class="selected-file">
        <div class="file-info">
          <el-icon>
            <Document />
          </el-icon>
          <span class="filename">{{ selectedFile.name }}</span>
        </div>
        <el-icon class="close-icon" @click="cancelFileUpload">
          <Close />
        </el-icon>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Document, Folder, Download, Close } from '@element-plus/icons-vue';
import { sendMsg } from '@/api/aircraft';
import defaultAvatar from '@/assets/images/users.png';
import moment from 'moment';

const props = defineProps({
  flightNo: {
    type: String,
    default: '20250603_B12PW_01'
  },
  active: {
    type: Boolean,
    default: false
  }
});

const loading = ref(false);
const inputMessage = ref('');
const messages = ref([]);
const messageListRef = ref(null);
const selectedFile = ref(null);
let eventSource = null;

watch(() => props.active, (newVal) => {
  if (newVal && props.flightNo) {
    initEventSource();
    scrollToBottom();
  } else {
    closeEventSource();
  }
});

watch(() => props.flightNo, (newVal) => {
  if (newVal && props.active) {
    initEventSource();
  } else {
    closeEventSource();
  }
  messages.value = [];
});

// 处理图片加载错误
const handleImageError = (e) => {
  e.target.src = defaultAvatar;
};

// 处理媒体加载完成
const handleMediaLoaded = () => {
  nextTick(() => {
    scrollToBottom();
  });
};

// 使用moment格式化时间
const formatTime = (time) => {
  const now = moment();
  const date = moment(time);
  const diff = now.diff(date, 'days');

  // 今天内的消息显示时间
  if (diff < 1) {
    return date.format('HH:mm');
  }

  // 一周内的消息显示月日 时间
  if (diff < 7) {
    const weekDay = date.format('d');
    const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
    return `星期${weekDays[weekDay]} ${date.format('HH:mm')}`;
  } else if(diff < 7) {
    return date.format('MM月DD日 HH:mm');
  }

  // 更早的消息显示完整日期
  return date.format('YY年MM月DD日 HH:mm');
};

// 获取媒体文件的URL
const getMediaUrl = (file) => {
  if (file && file.url) {
    return `${import.meta.env.VITE_WEB_BASE_API}/${file.url}`;
  }

  return '';
};

// 下载文件
const downloadFile = (file) => {
  if (!file || !file.url) {
    ElMessage.error('文件路径无效');
    return;
  }

  try {
    // 构建下载链接
    const downloadUrl = `${import.meta.env.VITE_WEB_BASE_API}/${file.url}`;

    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = file.filename || '未知文件';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error('下载文件失败:', error);
    ElMessage.error('下载文件失败，请重试');
  }
};

// 处理文件选择
const handleFileChange = (file) => {
  selectedFile.value = file.raw;
};

// 取消文件上传
const cancelFileUpload = () => {
  selectedFile.value = null;
};

// 上传文件
const uploadFile = async () => {
  if (!selectedFile.value) return null;

  try {
    const formData = new FormData();
    formData.append('file', selectedFile.value);
    formData.append('fn', props.flightNo);

    // 调用上传文件API
    const response = await fetch(`${import.meta.env.VITE_WEB_BASE_API}/file/upload`, {
      method: 'POST',
      body: formData
    });

    if (!response.ok) {
      throw new Error('文件上传失败');
    }

    const result = await response.json();
    return result;
  } catch (error) {
    console.error('文件上传错误:', error);
    ElMessage.error('文件上传失败，请重试');
    return null;
  }
};

const sendMessage = async () => {
  if ((!inputMessage.value.trim() && !selectedFile.value) || !props.flightNo) return;

  try {
    loading.value = true;

    let fileInfo = null;
    // 如果有选择文件，先上传文件
    if (selectedFile.value) {
      fileInfo = await uploadFile();
      if (!fileInfo) {
        loading.value = false;
        return;
      }
    }

    const messageContent = inputMessage.value.replace(/\n/g, '').trim();

    // 添加到本地消息列表
    const newMessage = {
      id: Date.now(),
      sender: '我',
      content: messageContent,
      file: fileInfo,
      time: new Date(),
      type: 'sent'
    };

    messages.value.push(newMessage);
    inputMessage.value = '';
    selectedFile.value = null;

    await nextTick();
    scrollToBottom();

    // 发送文本消息
    if (messageContent) {
      await sendMsg({
        fn: props.flightNo,
        content: messageContent,
        sender: '操作员'
      });
    }

  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 初始化SSE连接
const initEventSource = () => {
  if (!props.flightNo) return;
  try {
    closeEventSource();

    const apiUrl = `${import.meta.env.VITE_WEB_BASE_API}/message/realtime/sse?fn=${props.flightNo}`;
    eventSource = new EventSource(apiUrl);

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data).sort((a, b) => a.epoch - b.epoch);
        // 日期排序

        console.log('收到消息:', data);
        if (!data || !Array.isArray(data) || data.length === 0) return;

        // 处理接收到的消息数组
        data.forEach(msg => {
          if (!msg) return;

          const receivedMessage = {
            id: Date.now() + Math.random(),
            sender: msg.source || '系统',
            content: msg.content || msg.message || '',
            file: msg.file || null,
            time: msg.epoch || new Date(),
            type: msg.self ? 'sent' : 'received',
            avatar: msg.avatar || null
          };

          messages.value.push(receivedMessage);
        });

        // 如果当前标签页处于活动状态，滚动到底部
        if (props.active) {
          nextTick(() => {
            scrollToBottom();
          });
        }
      } catch (err) {
        console.error('解析消息数据失败:', err);
      }
    };

    eventSource.onerror = (error) => {
      console.error('SSE连接错误:', error);
      closeEventSource();

      // 5秒后尝试重新连接
      // setTimeout(() => {
      //   if (props.active && props.flightNo) {
      //     initEventSource();
      //   }
      // }, 5000);
    };

  } catch (error) {
    console.error('初始化SSE连接失败:', error);
  }
};

// 关闭SSE连接
const closeEventSource = () => {
  if (eventSource) {
    eventSource.close();
    eventSource = null;
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
  }
};

onMounted(() => {
  if (props.active && props.flightNo) {
    initEventSource();
  }
});

onUnmounted(() => {
  closeEventSource();
});
</script>

<style lang="scss" scoped>
.message-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f7fa;
  overflow: hidden;

  .message-container {
    flex: 1;
    overflow: hidden;
    padding: 10px 0 10px 15px;
    position: relative;

    .message-list {
      padding-right: 15px;
      height: 100%;
      overflow-y: auto;
      padding-bottom: 10px;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: rgba(0, 0, 0, 0.2);
        border-radius: 4px;
      }

      .empty-message {
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .message-input {
    padding: 10px 15px;
    background-color: #fff;
    border-top: 1px solid #ebeef5;
    flex-shrink: 0;
    position: relative;

    .el-textarea :deep(.el-textarea__inner) {
      border-radius: 4px;
      resize: none;
      max-height: 80px;

      &:focus {
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }
    }

    .message-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 8px;

      .tip {
        font-size: 12px;
        color: #909399;
      }

      .action-buttons {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .file-upload {
        :deep(.el-upload) {
          display: flex;
        }

        .el-button {
          padding: 8px 12px;
        }
      }

      .el-button {
        border-radius: 4px;
        padding: 8px 15px;
      }
    }

    .selected-file {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 8px;
      padding: 5px 10px;
      background-color: #f2f6fc;
      border-radius: 4px;

      .file-info {
        display: flex;
        align-items: center;
        gap: 5px;
        color: #606266;
        font-size: 12px;

        .filename {
          max-width: 200px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .close-icon {
        cursor: pointer;
        color: #909399;

        &:hover {
          color: #f56c6c;
        }
      }
    }
  }

  .message-item {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }

    .message-row {
      display: flex;
      width: 100%;
      align-items: flex-end;
    }

    .avatar {
      width: 30px;
      height: 30px;
      border-radius: 3px;
      overflow: hidden;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .message-content {
      max-width: calc(100% - 60px);

      .sender-name {
        font-size: 10px;
        color: #999;
        padding-left: 5px;
        margin-bottom: 2px;
      }

      .bubble-wrapper {
        display: flex;
        align-items: flex-end;
      }

      .message-bubble {
        padding: 6px 9px;
        word-break: break-word;
        line-height: 1.4;
        font-size: 14px;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
        max-width: 100%;
      }

      .media-container {
        width: 100%;
        background-color: white;
        border-radius: 8px;

        // box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
        .el-image {
          width: 160px;
        }

        .file-item {
          display: flex;
          align-items: center;
          padding: 8px;
          cursor: pointer;
          border-radius: 4px;
          transition: background-color 0.2s;

          &:hover {
            background-color: #f5f7fa;
          }

          .file-icon {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #f2f6fc;
            border-radius: 4px;
            margin-right: 10px;
            color: #409eff;
            font-size: 20px;
          }

          .file-info {
            flex: 1;
            overflow: hidden;

            .file-name {
              font-size: 14px;
              color: #303133;
              margin-bottom: 4px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }

            .file-action {
              font-size: 12px;
              color: #409eff;
            }
          }
        }

        .video-container,
        .audio-container {
          width: 100%;

          .media-player {
            width: 100%;
            border-radius: 4px;
            max-height: 250px;
          }

          .media-action {
            margin-top: 5px;
            text-align: right;
            font-size: 12px;
            color: #409eff;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 4px;

            &:hover {
              text-decoration: underline;
            }
          }
        }

        .video-container {
          max-width: 300px;
        }

        .audio-container {
          width: 300px;

          audio {
            width: 100%;
          }
        }
      }

      .message-time {
        font-size: 10px;
        color: #b2b2b2;
        padding: 0 5px;
        margin-bottom: 4px;
        white-space: nowrap;
      }
    }

    &.received {
      .message-content {
        margin-left: 10px;
      }

      .message-bubble {
        background-color: white;
        border-radius: 0 8px 8px 8px;
        position: relative;

        &:before {
          content: '';
          position: absolute;
          left: -6px;
          top: 14px;
          width: 0;
          height: 0;
          border-top: 6px solid transparent;
          border-right: 8px solid white;
          border-bottom: 6px solid transparent;
        }
      }

      .media-container {
        border-radius: 0 8px 8px 8px;
        position: relative;

        &:before {
          content: '';
          position: absolute;
          left: -6px;
          bottom: 14px;
          width: 0;
          height: 0;
          border-top: 6px solid transparent;
          border-right: 8px solid white;
          border-bottom: 6px solid transparent;
        }
      }
    }

    &.sent {
      .message-row {
        justify-content: flex-end;
      }

      .message-content {
        margin-right: 10px;
        display: flex;
        flex-direction: column;
        align-items: flex-end;
      }

      .bubble-wrapper {
        flex-direction: row-reverse;
      }

      .message-bubble {
        background-color: #95ec69;
        border-radius: 8px 0 8px 8px;
        position: relative;

        &:after {
          content: '';
          position: absolute;
          right: -6px;
          top: 14px;
          width: 0;
          height: 0;
          border-top: 6px solid transparent;
          border-left: 8px solid #95ec69;
          border-bottom: 6px solid transparent;
        }
      }

      .media-container {
        background-color: #95ec69;
        border-radius: 8px 0 8px 8px;
        position: relative;

        &:after {
          content: '';
          position: absolute;
          right: -6px;
          bottom: 14px;
          width: 0;
          height: 0;
          border-top: 6px solid transparent;
          border-left: 8px solid #95ec69;
          border-bottom: 6px solid transparent;
        }
      }
    }
  }
}
</style>